package com.pdool.game.logic.handler.card;

import com.pdool.common.constants.ErrorCode;
import com.pdool.common.constants.MsgId;
import com.pdool.common.exception.ErrorException;
import com.pdool.common.msg.card.GroupRenameReq;
import com.pdool.common.msg.card.GroupRenameResp;
import com.pdool.game.core.msg.IHandler;
import com.pdool.game.core.msg.MsgHandler;
import com.pdool.game.logic.domain.entity.vo.CardGroupVo;
import com.pdool.game.logic.service.CardGroupService;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 卡组重命名
 */
@Component
@MsgHandler(MsgId.GROUP_RENAME)
public class GroupRenameHandler2003 implements IHandler<GroupRenameReq, GroupRenameResp> {
    @Resource
    CardGroupService cardGroupService;

    @Override
    public GroupRenameResp handle(Long roleId, GroupRenameReq req) {
        int groupIndex = req.getGroupIndex();
        String groupName = req.getGroupName();
        if (!StringUtils.hasText(groupName)) {
            throw new ErrorException(ErrorCode.WRONG_GROUP_NAME);
        }

        Map<Integer, CardGroupVo> allCardGroup = cardGroupService.allCardGroup(roleId);

        if (!allCardGroup.containsKey(groupIndex)) {
            throw new ErrorException(ErrorCode.NOT_EXIST_GROUP_INDEX);
        }
        CardGroupVo cardGroupVo = allCardGroup.get(groupIndex);
        cardGroupVo.getEntity().setGroupName(groupName);

        cardGroupService.updateCardGroup(allCardGroup, cardGroupVo);

        GroupRenameResp build = GroupRenameResp.newBuilder().setGroupName(groupName).setGroupIndex(groupIndex).build();

        return build;
    }
}